<template>
  <div class="albums-container">
    <app-header />
    <div class="main-content">
      <app-sidebar />
      <div class="album-content">
        <div class="album-header">
          <h2>相册</h2>
          <el-button type="primary" @click="showCreateDialog = true">
            <el-icon><Plus /></el-icon>
            创建相册
          </el-button>
        </div>
        
        <div class="album-grid" v-loading="albumStore.loading">
          <div 
            v-for="album in albumStore.albums" 
            :key="album.id" 
            class="album-card"
            @click="viewAlbum(album.id)"
          >
            <div class="album-cover">
              <img 
                v-if="album.cover_photo_path" 
                :src="album.cover_photo_path" 
                :alt="album.name"
              />
              <div v-else class="empty-cover">
                <el-icon size="48"><Picture /></el-icon>
              </div>
            </div>
            <div class="album-info">
              <h3>{{ album.name }}</h3>
              <p>{{ album.description || '暂无描述' }}</p>
              <div class="album-meta">
                <span>{{ album.photo_count || 0 }} 张照片</span>
                <span>{{ formatDate(album.created_at) }}</span>
              </div>
            </div>
            <div class="album-actions" @click.stop>
              <el-dropdown trigger="click">
                <el-button text>
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="editAlbum(album)">编辑</el-dropdown-item>
                    <el-dropdown-item @click="deleteAlbum(album.id)" divided>删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
        
        <el-pagination
          v-if="albumStore.pagination.totalPages > 1"
          v-model:current-page="albumStore.pagination.page"
          :page-size="albumStore.pagination.limit"
          :total="albumStore.pagination.total"
          layout="prev, pager, next, jumper, total"
          @current-change="handlePageChange"
        />
      </div>
    </div>
    
    <!-- 创建相册对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="创建相册"
      width="400px"
    >
      <el-form :model="newAlbum" label-width="80px">
        <el-form-item label="相册名称" required>
          <el-input v-model="newAlbum.name" placeholder="请输入相册名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="newAlbum.description"
            type="textarea"
            placeholder="请输入相册描述"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="createAlbum" :loading="creating">
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 编辑相册对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑相册"
      width="400px"
    >
      <el-form :model="editingAlbum" label-width="80px">
        <el-form-item label="相册名称" required>
          <el-input v-model="editingAlbum.name" placeholder="请输入相册名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="editingAlbum.description"
            type="textarea"
            placeholder="请输入相册描述"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="updateAlbum" :loading="updating">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Picture, MoreFilled } from '@element-plus/icons-vue'
import AppHeader from '../components/common/AppHeader.vue'
import AppSidebar from '../components/common/AppSidebar.vue'
import { useAlbumStore } from '../stores/album'
import { useAppStore } from '../stores/app'
import type { Album } from '../types'

// 使用状态管理和路由
const albumStore = useAlbumStore()
const appStore = useAppStore()
const router = useRouter()

// 对话框状态
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const creating = ref(false)
const updating = ref(false)

// 新建相册表单
const newAlbum = ref({
  name: '',
  description: ''
})

// 编辑相册表单
const editingAlbum = ref<Album>({
  id: 0,
  name: '',
  description: '',
  created_at: '',
  updated_at: ''
})

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

// 查看相册详情
const viewAlbum = (id: number) => {
  router.push(`/albums/${id}`)
}

// 创建相册
const createAlbum = async () => {
  if (!newAlbum.value.name.trim()) {
    ElMessage.warning('请输入相册名称')
    return
  }
  
  creating.value = true
  
  try {
    await albumStore.createAlbum(newAlbum.value.name, newAlbum.value.description)
    ElMessage.success('相册创建成功')
    showCreateDialog.value = false
    newAlbum.value = { name: '', description: '' }
  } catch (error) {
    ElMessage.error('创建相册失败')
  } finally {
    creating.value = false
  }
}

// 编辑相册
const editAlbum = (album: Album) => {
  editingAlbum.value = { ...album }
  showEditDialog.value = true
}

// 更新相册
const updateAlbum = async () => {
  if (!editingAlbum.value.name.trim()) {
    ElMessage.warning('请输入相册名称')
    return
  }
  
  updating.value = true
  
  try {
    await albumStore.updateAlbum(editingAlbum.value.id, {
      name: editingAlbum.value.name,
      description: editingAlbum.value.description
    })
    ElMessage.success('相册更新成功')
    showEditDialog.value = false
  } catch (error) {
    ElMessage.error('更新相册失败')
  } finally {
    updating.value = false
  }
}

// 删除相册
const deleteAlbum = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个相册吗？此操作不可恢复。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await albumStore.deleteAlbum(id)
    ElMessage.success('相册删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除相册失败')
    }
  }
}

// 处理分页变化
const handlePageChange = (page: number) => {
  albumStore.setPage(page)
  albumStore.fetchAlbums()
}

// 组件挂载时加载相册
onMounted(async () => {
  appStore.setCurrentPage('albums')
  
  try {
    await albumStore.fetchAlbums()
  } catch (error) {
    console.error('加载相册失败:', error)
  }
})
</script>

<style scoped>
.albums-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100vw;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.album-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 16px;
}

.album-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.album-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.album-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
  overflow-y: auto;
  flex: 1;
}

.album-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
  position: relative;
}

.album-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.album-cover {
  height: 180px;
  overflow: hidden;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.album-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.empty-cover {
  color: #c0c4cc;
}

.album-info {
  padding: 16px;
}

.album-info h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.album-info p {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #666;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.album-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

.album-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.album-card:hover .album-actions {
  opacity: 1;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>